package mall.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

import mall.bean.Cart;
import mall.bean.CartPK;
import mall.bean.Order;
import mall.bean.OrderItem;
import mall.bean.OrderState;
import mall.bean.Product;
import mall.dao.BaseDao;
import mall.dao.CartDao;
import mall.dao.OrderDao;
import mall.dao.OrderItemDao;
import mall.dao.ProductDao;
import mall.dao.impl.CartDaoImpl;
import mall.dao.impl.JdbcTemplate;
import mall.dao.impl.OrderDaoImpl;
import mall.dao.impl.OrderItemDaoImpl;
import mall.dao.impl.ProductDaoImpl;
import mall.service.OrderService;

public class OrderServiceImpl extends BaseServiceImpl<Order, Long> implements OrderService {
	
	// Service层调用Dao层
	private OrderDao orderDao = new OrderDaoImpl();
	private CartDao cartDao = new CartDaoImpl();
	private ProductDao productDao = new ProductDaoImpl();
	private OrderItemDao orderItemDao = new OrderItemDaoImpl();
	
	@Override
	public BaseDao<Order, Long> getDao() {
		return this.orderDao;
	}

	@Override
	public Order submitOrder(long uid)  {
		JdbcTemplate.startTransaction();
		// 根据uid查出他的cart记录, 计算出总金额
		List<Cart> cartItems = this.cartDao.findByUid(uid);
		BigDecimal totalAmount = new BigDecimal("0");
		for (Cart item : cartItems) {
			BigDecimal quantity = new BigDecimal(item.getQuantity());
			Product product = productDao.findById(item.getPid());
			BigDecimal price = product.getPrice();
			totalAmount.add(price.multiply(quantity));
		}
		// 插入订单
		Order order = new Order();
		order.setCreateTime(new Timestamp(System.currentTimeMillis()));
		order.setState(OrderState.TO_PAY);
		order.setTotalAmount(totalAmount);
		order.setUid(uid);
		orderDao.save(order);
		// 得到订单的编号oid
		long oid = JdbcTemplate.lastInsertId();
		order.setOid(oid);
		// 生成OrderItem
		for (Cart cartItem : cartItems) {
			OrderItem orderItem = new OrderItem();
			orderItem.setOid(oid);
			orderItem.setPid(cartItem.getPid());
			orderItem.setQuantity(cartItem.getQuantity());
			orderItemDao.save(orderItem);
		}
		// 扣减库存
		for (Cart cartItem : cartItems) {
			long pid = cartItem.getPid();
			Product product = productDao.findById(pid);
			product.setStock(product.getStock() - cartItem.getQuantity());
			productDao.update(product);
		}
		// 清除cart中的记录
		for (Cart cartItem : cartItems) {
			CartPK id = new CartPK(cartItem.getUid(), cartItem.getPid());
			cartDao.delete(id);
		}
		JdbcTemplate.commit();
		return order;
	}


}
